<?php

namespace App\Models\Plane\Comfort;

use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Plane\Comfort\PlaneComfort
 *
 * @property int $id
 * @property string $flight_no 航班号
 * @property string $flight_year 飞行时间
 * @property string $cancel_rate 取消率
 * @property string $from_punctuality_rate 出发准点
 * @property string $to_punctuality_rate 到达准点
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read Collection<int, PlaneComfortCabins> $cabins
 * @property-read int|null $cabins_count
 * @method static Builder|PlaneComfort newModelQuery()
 * @method static Builder|PlaneComfort newQuery()
 * @method static Builder|PlaneComfort query()
 * @method static Builder|PlaneComfort whereCancelRate($value)
 * @method static Builder|PlaneComfort whereCreatedAt($value)
 * @method static Builder|PlaneComfort whereFlightNo($value)
 * @method static Builder|PlaneComfort whereFlightYear($value)
 * @method static Builder|PlaneComfort whereFromPunctualityRate($value)
 * @method static Builder|PlaneComfort whereId($value)
 * @method static Builder|PlaneComfort whereToPunctualityRate($value)
 * @method static Builder|PlaneComfort whereUpdatedAt($value)
 * @mixin Eloquent
 */
class PlaneComfort extends Model
{
    use HasFactory;

    protected $table = 'plane_comfort';

    protected $fillable
        = [
            'flight_no',
            'flight_year',
            'cancel_rate',
            'from_punctuality_rate',
            'to_punctuality_rate',
        ];

    public function cabins()
    {
        return $this->hasMany(PlaneComfortCabins::class, 'flight_no', 'flight_no');
    }

    public function add(array $data): ?self
    {
        $ret = null;
        DB::transaction(function () use ($data, &$ret) {
            $cabins = $data['cabins'];
            unset($data['cabins']);
            if (!($comfort = $this->findByFlight($data['flight_no']))) {
                $comfort = $this->create($data);
            }
            $ret = $comfort;
            $ca  = new PlaneComfortCabins();
            foreach ($cabins as $cabin) {
                $ca->add($comfort, $cabin);
            }
        });
        return $ret;
    }


    public function findByFlight(string $flight_no)
    {
        $ck = "comfort:{$flight_no}";
        if (Cache::has($ck)) {
            return Cache::get($ck);
        }

        $cabin = $this->where([
            'flight_no' => $flight_no,
        ])->first();
        $cabin && Cache::put($ck, $cabin, config('trip.ttl.month'));
        return $cabin;


    }
}
